package titt.util.io.pipe;

import java.io.InputStream;
import java.io.OutputStream;

import titt.config.ValueConfig;

public class StreamPiperImpl extends UtilPiper implements StreamPiper {


	public void pipe(final InputStream in, final OutputStream out, int length, PipeListener pl) throws Exception {
		int buffer_size = ValueConfig.get().getBufferSize();

		int bytes_read = 0, just_read = 0, wanna_read = Math.min(length, buffer_size);

		byte[] buffer = new byte[buffer_size];

		if(pl != null) pl.onInitiate(length);

		try {
			
			while(wanna_read > 0 && (just_read = in.read(buffer, 0, wanna_read)) != -1) {//Thread.sleep(100);

				out.write(buffer, 0, just_read);

				bytes_read += just_read;

				wanna_read = Math.min(length-bytes_read, buffer_size);

				if(pl != null) pl.onConnectionUpdate(bytes_read, length);
			}
			
			out.flush();

			if(pl != null) pl.onComplete(length);

		}
		catch(Exception e) {
			if(pl != null) pl.onError();
			throw e;
		}

	}

}

